<template>
  <div>
    <div class="filter-container">
      <el-input v-model="listQuery.elementName" placeholder="请输入元素名称" size="medium" style="width: 200px;" class="filter-item" @keyup.native="handleFilter" />
      <el-select v-model="listQuery.type" placeholder="元素类型" clearable size="medium" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in elementType" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.locationBy" placeholder="定位类型" size="medium" clearable class="filter-item" style="width: 180px" @change="handleFilter">
        <el-option v-for="item in locationBy" :key="item.id" :label="item.cn_name" :value="item.id" />
      </el-select>
      <el-button :disabled="!addFlag" class="filter-item" size="medium" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="createHandle">
        新增元素
      </el-button>
      <el-dropdown @command="batchHandle">
        <el-button type="danger" size="medium">
          批量操作<i class="el-icon-arrow-down el-icon--right" />
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="del">批量删除</el-dropdown-item>
          <el-dropdown-item command="changePage">变更页面</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button class="filter-item" type="primary" icon="el-icon-refresh" size="medium" @click="refreshTable">
        刷新
      </el-button>
    </div>
    <el-table
      ref="dataTable"
      v-loading="listLoading"
      border
      highlight-current-row
      :data="pageData"
      style="width: 100%"
      @selection-change="selectRowHandle"
      @sort-change="tableSortChange"
    >
      <el-table-column
        type="selection"
        align="center"
        width="55"
      />
      <el-table-column
        prop="id"
        label="ID"
        align="center"
        sortable
        min-width="90"
      />
      <el-table-column
        prop="element_name"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        label="元素名称"
        min-width="180"
      />
      <el-table-column
        prop="type"
        sortable
        align="center"
        min-width="100"
        label="元素类型"
      />
      <el-table-column
        prop="location_by_id"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        min-width="100"
        label="定位类型"
      >
        <template slot-scope="scope">
          <span>{{ locationBy[scope.row.location_by_id] !== undefined ? locationBy[scope.row.location_by_id].cn_name : scope.row.location_by_id }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="by_value"
        sortable
        align="center"
        min-width="140"
        :show-overflow-tooltip="true"
        label="定位值"
      />
      <el-table-column
        prop="frame_name"
        align="center"
        sortable
        :show-overflow-tooltip="true"
        label="frame"
      />
      <el-table-column
        prop="create_time"
        sortable
        align="center"
        min-width="140"
        :show-overflow-tooltip="true"
        label="创建时间"
      />
      <el-table-column
        prop="creator_name"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        label="创建人"
      />
      <el-table-column
        prop="last_mender_name"
        sortable
        align="center"
        :show-overflow-tooltip="true"
        label="修改人"
      />
      <el-table-column
        prop="mark"
        :show-overflow-tooltip="true"
        sortable
        align="center"
        min-width="80"
        label="备注"
      />
      <el-table-column label="操作" fixed="right" header-align="center" align="center" min-width="120">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="updateHandle(scope.row)">编辑</el-button>
          <el-button v-if="addFlag" type="text" size="small" @click="copyHandle(scope.row)">复制</el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        :current-page="pageIndex"
        :page-sizes="[10, 15, 30, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog :title="edit.textMap[edit.status]" :visible.sync="edit.visible">
      <el-form ref="dataForm" :rules="edit.rules" :model="edit.temp" label-position="left" label-width="140px" style=" margin-left:20px;">
        <el-form-item label="元素名称" prop="element_name">
          <el-input v-model="edit.temp.element_name" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="元素类型" prop="type">
          <el-select v-model="edit.temp.type" class="filter-item" placeholder="请选择">
            <el-option v-for="item in elementType" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="定位类型" prop="location_by_id">
          <el-select v-model="edit.temp.location_by_id" class="filter-item" placeholder="请选择">
            <el-option v-for="item in locationBy" :key="item.cn_name" :label="item.cn_name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="定位值" prop="by_value">
          <el-input v-model="edit.temp.by_value" />
        </el-form-item>
        <el-form-item label="所属frame/iframe" prop="frame_id">
          <el-cascader
            v-model="edit.temp.frame_id"
            placeholder="请输入搜索关键字"
            :options="edit.webFrameOptions"
            :props="{ expandTrigger: 'hover', value: 'id', label: 'node_name'}"
            style="width:360px;"
            filterable
            :clearable="true"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="edit.temp.mark" :autosize="{ minRows: 4, maxRows: 8}" type="textarea" placeholder="输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="edit.visible = false">
          取消
        </el-button>
        <el-button size="medium" type="primary" @click="updateOrAddData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="选择需要变更到的页面"
      :visible.sync="choosePage.visible"
      width="28%"
      :close-on-click-modal="false"
      :center="true"
    >
      <el-cascader
        v-model="choosePage.value"
        placeholder="请输入搜索关键字"
        :options="choosePage.options"
        :props="{ expandTrigger: 'hover', value: 'id', label: 'node_name'}"
        style="width:300px;"
        filterable
      />
      <el-button type="primary" @click="saveChangePage">确定</el-button>
      <el-button @click="choosePage.visible=false">取消</el-button>
    </el-dialog>
  </div>
</template>

<script>
import { elementList, elementEdit, elementDel, getElementPageList, changeElementsPage } from '@/api/element'
import { parseTreeData } from '@/utils/commonUtil.js'
import mixinBaseView from '@/mixins/view-base.js'

export default {
  mixins: [mixinBaseView],
  props: {
    elementNode: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      commonPageSetting: {
        entityTitle: '页面元素',
        entityNameKey: 'element_name',
        entityIdKey: 'id',
        listApi: elementList,
        editApi: elementEdit,
        delApi: elementDel,
        beforeSendEdit(vm) {
          if (vm.elementNode === undefined) {
            vm.$message.error('当前节点不能添加页面元素')
            return false
          }
          if (vm.edit.temp.frame_id && vm.edit.temp.frame_id.length > 0) {
            vm.edit.temp.frame_id = vm.edit.temp.frame_id[vm.edit.temp.frame_id.length - 1]
          }
          return true
        },
        resetTemp(vm) {
          vm.edit.temp.page_id = vm.elementNode === undefined ? '' : vm.elementNode.id
        },
        afterOpenEdit(vm) {
          vm.getElementWebFrame()
        }
      },
      addFlag: false,
      nodeLevel: 2,
      listQuery: { // 查询条件
        elementName: '',
        type: '',
        locationBy: ''
      },
      // 编辑/新增表单
      edit: {
        textMap: {
          update: '编辑元素信息',
          create: '新增元素信息',
          copy: '复制元素信息'
        },
        temp: {
          id: undefined,
          element_name: '',
          type: this.$store.state.user.dictConfig.elementType[0],
          location_by_id: 7,
          by_value: '',
          frame_id: undefined,
          mark: '',
          frame_name: '',
          page_id: this.elementNode === undefined ? '' : this.elementNode.id
        },
        rules: {
          element_name: [{ required: true, message: '请输入元素名称', trigger: 'change' }],
          type: [{ required: true, message: '请选择元素类型', trigger: 'change' }],
          location_by_id: [{ required: true, message: '请选择定位类型', trigger: 'change' }],
          by_value: [{ required: true, message: '请输入定位值', trigger: 'change' }]
        },
        webFrameOptions: []
      },
      choosePage: {
        visible: false,
        value: undefined,
        options: []
      }
    }
  },
  computed: {
    locationBy() {
      return this.$store.state.user.dictConfig.locationBy
    },
    elementType() {
      return this.$store.state.user.dictConfig.elementType
    },
    listParams() {
      const params = {}
      if (this.elementNode !== undefined) {
        if (this.elementNode.node_level === 1) {
          params.system_id = this.elementNode.id
        } else if (this.elementNode.node_level === 2) {
          params.node_id = this.elementNode.id
        }
      }
      return params
    }
  },
  watch: {
    'elementNode.id': function() {
      if (this.elementNode.node_level !== 2) {
        this.addFlag = false
      } else {
        this.addFlag = true
      }
      this.getData()
    }
  },
  methods: {
    async getElementWebFrame() {
      let webFrames = []
      await elementList({ type: 'web_frame' }).then(response => {
        webFrames = response.data
      })
      if (webFrames.length > 0) {
        getElementPageList().then(response => {
          const data = response.data
          this.edit.webFrameOptions = parseTreeData(data.filter(item => item.node_level === 0), data, (item, node) => item.parent_node_id === node.id
            , item => {
              if (item.node_level === 2) {
                item.children = webFrames.filter(frame => {
                  if (frame.page_id === item.id) {
                    frame.node_name = frame.element_name
                    return true
                  }
                  return false
                })
              }
              if (item.children === undefined || item.children.length === 0) {
                item.disabled = true
              }
            }, true
          )
        })
      }
    },
    // 复制
    copyHandle(row) {
      this.getElementWebFrame()
      this.edit.visible = true
      this.edit.status = 'copy'
      Object.assign(this.edit.temp, row)
      this.edit.temp.id = undefined
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate()
      })
    },
    // 过滤
    selfHandleFilter(data) {
      if (this.listQuery.elementName !== '') {
        data = data.filter(item => item.element_name.indexOf(this.listQuery.elementName) !== -1)
      }
      if (this.listQuery.type !== '') {
        data = data.filter(item => item.type === this.listQuery.type)
      }
      if (this.listQuery.locationBy !== '') {
        data = data.filter(item => item.location_by_id === this.listQuery.locationBy)
      }
      return data
    },
    // 批量操作
    batchHandle(key) {
      if (this.selectIds.length === 0) {
        this.$message.warning('请先选择至少一行数据!')
        return
      }
      if (key === 'changePage') {
        this.choosePage.value = undefined
        this.choosePage.visible = true
        const thisPageId = this.elementNode !== undefined ? this.elementNode.id : undefined
        getElementPageList().then(response => {
          this.choosePage.options = parseTreeData(response.data.filter(item => item.node_level === 0), response.data
            , (item, node) => item.parent_node_id === node.id
            , item => {
              if ((item.node_level === 2 && item.id === thisPageId) || (item.node_level === 1 && item.children === undefined)) {
                item.disabled = true
              }
            }, true)
        })
      }
      if (key === 'del') {
        this.batchDel()
      }
    },
    // 保存选择变更的页面
    saveChangePage() {
      if (!(this.choosePage.value instanceof Array)) {
        this.$message.warning('请先选择需要变更到的页面!')
        return
      }
      changeElementsPage(this.choosePage.value.pop(), this.selectIds).then(response => {
        this.choosePage.visible = false
        this.getData()
        this.$message.success('变更页面成功')
      })
    }
  }
}
</script>

<style scoped>
  .el-dropdown {
    vertical-align: top;
  }
</style>
